package com.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.NewsList;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@Slf4j
@Component
public class SchedulingCrawlerService {

    private final Logger logger = LoggerFactory.getLogger(SchedulingCrawlerService.class);


    @Autowired
    public ToFileService service;


    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    private CrawlerUpdateServive crawlerUpdateServive;


    //  定时任务抓取，任务分解
//    1、每个类别是否 有更新，有更新在做更新操作
//    1.2、若没更新，则不做更新操作
//    2、需要更新，更新那几条，与数据库进行对比

    @Scheduled(cron = "00 08 11 * * ?")  // 定时规则 :每日 3:00 执行任务
    public void scheduCrawler() {  //account  是抓取的页数
        logger.debug("开始执行 爬取定时任务 --->");
        System.out.println("开始爬取");
        for (int i = 1; i <= 7; i++) {
            crawlerUpdateServive.isUpdate(i);
        }
        System.out.println("爬取完毕");
        logger.debug("爬取任务执行完毕 --->");

    }

    public void tofiles() throws IOException {
        String path = "/www/wwwroot/39.96.43.67/ChangDeNews/files";
        String typeDec = "null";
        System.out.println("开始制作json...");
        for (int i = 1; i < 8; i++) {
            List<NewsList> top30 = service.findTop30(i);

            Iterator<NewsList> iterator = top30.iterator();
            while (iterator.hasNext()) {
                NewsList next = iterator.next();
                if (next == null) {
                    iterator.remove();
                } else {
                    String replace = next.getUrl().replace("http://nyncj.changde.gov.cn", "");
                    next.setUrl(replace);
                }
            }


            switch (i) {
                case 1:
                    typeDec = "常德动态";
                    break;
                case 2:
                    typeDec = "乡村振兴";
                    break;
                case 3:
                    typeDec = "农事指导";
                    break;
                case 4:
                    typeDec = "现代农业";
                    break;
                case 5:
                    typeDec = "质量安全";
                    break;
                case 6:
                    typeDec = "三农论坛";
                    break;
                case 7:
                    typeDec = "领导言论";
                    break;
            }

            File file = new File(path, typeDec + ".json");
            if (!file.exists()) {
                file.createNewFile();
            }
            objectMapper.writeValue(file, top30);
        }
    }
}
